//
//  WebService.m
//  WeddingStoreFinder
//
//  Created by Macdev on 11/19/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "WebService.h"
#import "JSON.h"


@interface WebService()

@property (nonatomic, retain) CustomReachability *netCheck;

@property int errorCode;

- (void) anErrorOccurred:(NSString*)errorDescription;
- (void) sendRequestToServer;

@end

@implementation WebService

@synthesize isOK, receivedData, done, wsType, jsonResult;
@synthesize  delegate, netCheck, wsError, errorCode;

- (void) dealloc
{
	[jsonResult release];
	[receivedData release];
	[netCheck release];
	[wsError release];
	[super dealloc];
}

- (id) init {
	self = [super init];
	if ( self ) {
		NSMutableData *dataTemp = [[NSMutableData alloc] init];
		self.receivedData = dataTemp;
		[dataTemp release];
    }
    return self;
}

- (void) sendRequest {
	CustomReachability *reach = [[CustomReachability alloc] init];
	reach.delegate = self;
	self.netCheck = reach;
	[reach release];
	[netCheck checkInternetConnection];
}


- (void) sendRequestToServer {
	NSData *data = nil;
	@try {
		
		isOK = TRUE;
		done = NO;
		//NSURLResponse *response;
		//NSError *error = nil;
		NSString *urlString = @"";
		switch (wsType) {
			case kWSType_CheckForUpdate:
				urlString = [NSString stringWithFormat:@"%@%@", kURL_Base, kURLSuffix_CheckForUpdate];
				break;
			case kWSType_UpdatePOI:
				urlString = [kURL_Base stringByAppendingFormat:@"%@%@", kURLSuffix_UpdatePOI, [AppConf getStringForKey:kAppConfKey_LastUpdateTimeStamp]];
				break;
			case kWSType_UpdateDress:
				urlString = [kURL_Base stringByAppendingFormat:@"%@%@", kURLSuffix_UpdateDress, [AppConf getStringForKey:kAppConfKey_LastUpdateTimeStamp]];
				break;
			default:
				break;
		}
		
		NSLog(@"url: %@", urlString);
		NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
		[theRequest setHTTPMethod:@"GET"];
		//[theRequest addValue:[NSString stringWithFormat:@"gzip"] forHTTPHeaderField:@"Accept-Encoding"];
	
		//aszinkron request
		NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
		[theConnection release];
	}
	@catch (NSException * e) {
		NSLog(@"Exception(WebService-sendRequest): %@", [e reason]);
		if (isOK) {
			isOK = FALSE;
			[self performSelectorOnMainThread:@selector(anErrorOccurred:) withObject:@"Unknown error occurred, please try again later!" waitUntilDone:YES];
		}
		
	}
	@finally {
		[data release];
	}
}




- (void) anErrorOccurred:(NSString*)errorDescription {
	
	NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errorDescription forKey:NSLocalizedDescriptionKey];
	self.wsError = [NSError errorWithDomain:NSCocoaErrorDomain code:self.errorCode userInfo:userInfo];
	[self.delegate anErrorOccurred:self];
	
}

- (void) allWentOK {
	[self.delegate allWentOK:self];
}



#pragma mark - NSURLConnection delegate



// Forward errors to the delegate.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    done = YES;
	if (isOK) {
		isOK = FALSE;
		self.errorCode = [error code];
		[self performSelectorOnMainThread:@selector(anErrorOccurred:) withObject:@"Unknown error occurred, please try again later!" waitUntilDone:YES];
		
	}
	

	
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
	return YES;
}


// Called when a chunk of data has been downloaded.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //done = YES; 
	[receivedData appendData:data];
	
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	@try {
		NSString *jsonString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
		SBJSON *parser = [[SBJSON alloc] init];
		NSLog(@"resp: %@", jsonString);
		self.jsonResult = [parser objectWithString:jsonString];
		if ([jsonResult valueForKey:kJSON_response] != nil) {
			if ([[jsonResult valueForKey:kJSON_response] isKindOfClass:[NSDictionary class]] && [[jsonResult valueForKey:kJSON_response] valueForKey:kJSON_containsError] != nil) {
				[self performSelectorOnMainThread:@selector(anErrorOccurred:) withObject:[[[jsonResult valueForKey:kJSON_response] valueForKey:kJSON_error] valueForKey:kJSON_errorMessage] waitUntilDone:YES];
			} else {
				[self performSelectorOnMainThread:@selector(allWentOK) withObject:self waitUntilDone:YES];
			}
			
		} else {
			[self performSelectorOnMainThread:@selector(anErrorOccurred:) withObject:@"Unknown error occurred, please try again later!" waitUntilDone:YES];
		}
		
		
		
		[parser release];
		[jsonString release];
		done = YES;
	}
	@catch (NSException *exception) {
		[self performSelectorOnMainThread:@selector(anErrorOccurred:) withObject:@"Unknown error occurred, please try again later!" waitUntilDone:YES];
	}
	@finally {
		
	}
	 
}

#pragma mark - ReachabilityDelegate

- (void) connectionOff:(CustomReachability*)reachability {
	NSString *errorMSG = @"You need internet connection for download updates!";
	
	NSDictionary *userInfo = [NSDictionary dictionaryWithObject:errorMSG forKey:NSLocalizedDescriptionKey];
	self.wsError = [NSError errorWithDomain:NSCocoaErrorDomain code:kErrorCode_NoConnection userInfo:userInfo];
	[self performSelectorOnMainThread:@selector(networkUnavailable) withObject:nil waitUntilDone:NO];
}

- (void) connectionOn:(CustomReachability*)reachability {
	[self sendRequestToServer];
}

- (void) networkUnavailable {
	[self.delegate networkUnavailable:self];
}

@end
